package com.example.zqh.service.impl;

import com.example.zqh.mapper.UserMapper;
import com.example.zqh.pojo.User;
import com.example.zqh.pojo.params.UserPlus;
import com.example.zqh.utils.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zqh
 * @Date: 2022-07-27-9:35
 * @Description: 重写UserDetailsService$
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //如果用户名不为空，通过用户名查询此用户
        AssertUtil.isTrue(username!=null&&"".equals(username),"用户不存在");
        User user = userMapper.getOneByUsername(username);

        //通过用户名查询该用户拥有的权限
        List<String> list = userMapper.getRoleCodeByUsername(username);


        //把权限装入一个ArrayList里面,等着把这个权限放入userplus里面
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (String s : list) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(s);
            grantedAuthorities.add(authority);
        }

        //返回用户的所有信息
        UserPlus userPlus = new UserPlus();
        userPlus.setAuthorities(grantedAuthorities);
        userPlus.setName(user.getName())
                .setPassword(user.getPassword())
                .setSex(user.getSex())
                .setAddress(user.getAddress())
                .setHeadUrl(user.getHeadUrl())
                .setIntro(user.getIntro())
                .setPhone(user.getPhone())
                .setId(user.getId());
        return userPlus;
    }
}
